package com.zhengdongzulin.zuke.app.work.activity

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.lxj.androidktx.core.getVM
import com.lxj.androidktx.core.sp
import com.lxj.androidktx.livedata.StateLiveData
import com.zhengdongzulin.zuke.R
import com.zhengdongzulin.zuke.app.data.UserInfo
import com.zhengdongzulin.zuke.app.work.vm.ZKAddWorkVM
import com.zhengdongzulin.zuke.base.BaseActivity
import com.zhengdongzulin.zuke.databinding.ZkActivityAddWorkBinding
import com.zhengdongzulin.zuke.databinding.ZkPopwindowWorkAddChooseLaiyuanBinding
import com.zhengdongzulin.zuke.ext.*
import com.zhengdongzulin.zuke.picture.GlideEngine
import java.io.File

/**
 * @类名称: CLASS
 * @类描述:
 * @创建人：Jeff
 * @创建时间：2021/6/9 20:53
 * @备注：
 */
class ZKAddWorkActivity :
    BaseActivity<ZKAddWorkVM, ZkActivityAddWorkBinding>() {

    private var intentType: String? = ""
    private var picList: MutableList<LocalMedia> = mutableListOf<LocalMedia>().apply {
        add(0, LocalMedia().apply {
            path = "0"
        })
    }

    override fun getLayoutResId(): Int = R.layout.zk_activity_add_work

    override fun initVM(): ZKAddWorkVM = getVM(ZKAddWorkVM::class.java)

    override fun initView() {

        intentType = intent.getStringExtra("type")

        when (intentType) {
            "Baoshi" -> {
                setTitleContent("报事报修")
                mView.ivType.setImageResource(R.drawable.icon_work_entrance_baoxiu)
                mView.tvType.text = "报事工单"
                mView.tvLaiyuanTitle.text = "服务申请"
                mView.tvQuyu.text = "报事"
            }
            "Weixiu" -> {
                setTitleContent("维修工单")
                mView.ivType.setImageResource(R.drawable.icon_work_entrance_baoxiu)
                mView.tvType.text = "维修工单"
                mView.tvLaiyuanTitle.text = "服务申请"
                mView.tvQuyu.text = "物业报修"
            }
            "Baojie" -> {
                setTitleContent("服务申请")
                mView.ivType.setImageResource(R.drawable.icon_work_entrance_baojie)
                mView.tvType.text = "服务申请"
                mView.tvLaiyuanTitle.text = "服务申请"
                mView.tvQuyu.text = "保洁申请"
            }
            "Kongtiao" -> {
                setTitleContent("服务申请")
                mView.ivType.setImageResource(R.drawable.icon_work_entrance_kongtiao)
                mView.tvType.text = "服务申请"
                mView.tvLaiyuanTitle.text = "服务申请"
                mView.tvQuyu.text = "空调申请"
            }
        }

        var user = sp().getString("userInfo", "")
        if (!user.isNullOrEmpty()) {
            var userInfo = Gson().fromJson<UserInfo>(user, UserInfo::class.java)
            mView.etName.setText(userInfo.nameCn)
            mView.etPhone.setText(userInfo.phone)
        }

        mView.ok.setBackgroundDrawable(GradientDrawable().apply {
            setColor(Color.parseColor("#1273f7"))
            cornerRadius = 10.0f
        })
        mView.recyclerViewAddPic.apply {

            layoutManager = GridLayoutManager(this@ZKAddWorkActivity, 4)
            adapter = VPicAdpater(picList).apply {
                setClick(object : Click {
                    override fun delete(int: Int) {
                        picList.removeAt(int)
                        if (picList.filter {
                                "0".equals(it.path)
                            }.size == 0) {
                            picList.add(picList.size, LocalMedia().apply {
                                path = "0"
                            })
                        }
                        notifyItemRemoved(int)
                    }

                    override fun choose() {
                        PictureSelector.create(this@ZKAddWorkActivity)
                            .openGallery(PictureMimeType.ofImage())
                            .imageEngine(GlideEngine.createGlideEngine())
                            .isCompress(true)//是否压缩
                            .compressQuality(60)//图片压缩后输出质量
                            .synOrAsy(false)//开启同步or异步压缩
                            .maxSelectNum(limitSize)
                            .selectionData(picList.filter {
                                !"0".equals(it.path)
                            })
                            .forResult(object : OnResultCallbackListener<LocalMedia> {
                                override fun onCancel() {}
                                override fun onResult(result: MutableList<LocalMedia>) {
                                    picList.clear()
                                    picList.addAll(result)
                                    if (picList.size < 5) {
                                        picList.add(picList.size, LocalMedia().apply {
                                            path = "0"
                                        })
                                    }
                                    notifyDataSetChanged()
                                }
                            })
                    }
                })
            }
        }
    }

    override fun initData() {

    }

    override fun initListener() {
        mView.ok.setOnClickListener {

            if (TextUtils.isEmpty(mView.etName.getTextZ())) {
                ToastUtils.showLong("请输入申请人")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(mView.etPhone.getTextZ())) {
                ToastUtils.showLong("请输入联系电话")
                return@setOnClickListener
            }
            if (!mView.etPhone.checkPhone()) {
                ToastUtils.showLong("请输入正确的手机号")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(mView.etMiaoshu.getTextZ())) {
                ToastUtils.showLong("请输入详细描述")
                return@setOnClickListener
            }
//            if (picList.filter {
//                    !"0".equals(it.path)
//                }.size == 0) {
//                ToastUtils.showLong("请选择图片")
//                return@setOnClickListener
//            }

            mView.ok.isClickable = false

            var fils: ArrayList<File> = arrayListOf()
            picList.filter {
                !"0".equals(it.path)
            }.forEach {
                fils.add(File(it.getFilePath()))
            }
            mViewModel.create_gong_dan(
                incidentType = mView.tvType.getTextZ(),
                title = mView.tvQuyu.getTextZ(),
                linkmanName = mView.etName.getTextZ(),
                linkmanPhone = mView.etPhone.getTextZ(),
                description = mView.etMiaoshu.getTextZ(),
                imgList = fils
            )
        }

//        mView.cvType.setOnClickListener {
//            var view = ZkPopwindowWorkAddChooseTypeBinding.inflate(layoutInflater)
//
//            var dialog = getBottomDialog(view.root, 0.0)
//            dialog.setCanceledOnTouchOutside(true)
//
//
//            when (intentType) {
//                "Baoshi" -> {
//                    view.llBaoshiBaoxiu.visibility = View.VISIBLE
//                    view.tvFuwu.visibility = View.GONE
//
//                    view.tvBaoshi.setOnClickListener {
//                        dialog.dismiss()
//                        mView.tvType.text = view.tvBaoshi.getTextZ()
//                        mView.tvQuyu.text = "报事"
//                        mView.tvLaiyuanTitle.text = "报事来源"
//                    }
//                    view.tvWeixiu.setOnClickListener {
//                        dialog.dismiss()
//                        mView.tvType.text = view.tvWeixiu.getTextZ()
//                        mView.tvQuyu.text = "报修"
//                        mView.tvLaiyuanTitle.text = "报修来源"
//                    }
//                }
//                "Baojie" -> {
//                    view.llBaoshiBaoxiu.visibility = View.GONE
//                    view.tvFuwu.visibility = View.VISIBLE
//
//                    view.tvFuwu.setOnClickListener {
//                        dialog.dismiss()
//                        mView.tvType.text = view.tvFuwu.getTextZ()
//                        mView.tvQuyu.text = "保洁申请"
//                    }
//                }
//            }
//
//            view.tvCancel.setOnClickListener {
//                dialog.dismiss()
//            }
//            dialog.show()
//        }

        mView.llBaoXiuLaiYuan.setOnClickListener {

            var view = ZkPopwindowWorkAddChooseLaiyuanBinding.inflate(layoutInflater)

            var dialog = getBottomDialog(view.root, 0.0)
            dialog.setCanceledOnTouchOutside(true)

            when (mView.tvType.getTextZ()) {
                "报事工单" -> {
                    view.tv1.text = "报事"
                    view.tv2.visibility = View.GONE
                }
                "维修工单" -> {
                    view.tv1.text = "物业报修"
                    view.tv2.text = "客户投诉"
                }
                "服务申请" -> {
                    view.tv1.text = "保洁申请"
                    view.tv2.text = "空调申请"
                }
            }
            view.tv1.setOnClickListener {
                dialog.dismiss()
                mView.tvQuyu.text = view.tv1.getTextZ()
            }
            view.tv2.setOnClickListener {
                dialog.dismiss()
                mView.tvQuyu.text = view.tv2.getTextZ()
            }
            view.tvCancel.setOnClickListener {
                dialog.dismiss()
            }
            dialog.show()

        }
    }

    override fun startObserve() {
        mViewModel.createSuccess.observe(this, Observer {
            mView.ok.isClickable = true
            Intent().start(this, ZKAddWorkSuccessActivity::class.java)
            finish()
        })
        mViewModel.createSuccess.state.observe(this, Observer {
            when (it) {
                StateLiveData.State.Error -> ToastUtils.showShort("创建失败")
                StateLiveData.State.Empty -> ToastUtils.showShort("创建失败")
            }
            mView.ok.isClickable = true
        })
    }

    var limitSize = 5

    interface Click {
        fun delete(int: Int)
        fun choose()
    }

    inner class VPicAdpater(
        list: MutableList<LocalMedia>
    ) : BaseQuickAdapter<LocalMedia, BaseViewHolder>(
        R.layout.zk_item_add_work_choose_pic,
        list
    ) {
        var mclick: Click? = null

        fun setClick(click: Click) {
            this.mclick = click
        }

        override fun convert(holder: BaseViewHolder, item: LocalMedia) {
            if ("0".equals(item.path)) {
                holder.loadImage(
                    R.id.photo,
                    R.drawable.zk_icon_add_work_choose_pic,
                    R.mipmap.error_empty_zheng
                )
                holder.getView<ImageView>(R.id.delete).visibility = View.GONE
            } else {
                holder.loadImage(
                    R.id.photo,
                    item.path,
                    R.mipmap.error_empty_zheng,
                    6.0f
                )
                holder.getView<ImageView>(R.id.delete).visibility = View.VISIBLE
            }
            holder.getView<ImageView>(R.id.delete).setOnClickListener {
                mclick?.delete(holder.position)
            }
            holder.getView<ImageView>(R.id.photo).setOnClickListener {
                mclick?.choose()
            }
        }
    }
}

